import HandleBtn from '@/components/HandleBar/btn';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  historyDataControllerBmsHistoryData,
  historyDataControllerHistoryDataExport as exportDataReport,
} from '@/services/ess/historicalData';
import { downloadFetch } from '@/utils/downloadFile';
import { Link, useIntl } from '@umijs/max';
import { message } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

interface Props {
  tabIndex?: string;
  deviceCode?: string;
  deviceType?: string;
  areaId?: string;
  selectedKeys?: string[];
}

const BatteryStackInfo: React.FC<Props> = ({ deviceCode, deviceType, areaId, selectedKeys }) => {
  const intl = useIntl();
  const [data, setData] = useState<API.BmsPageDataDTO[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    current: 1,
    pageSize: 20,
    startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
    endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
  });
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);

  const correctColumn: ProColumns = {
    title: intl.formatMessage({ id: 'data.available' }),
    dataIndex: 'correct',
    valueType: 'select',
    valueEnum: {
      1: {
        text: intl.formatMessage({ id: 'data.effective' }),
      },
      0: {
        text: intl.formatMessage({ id: 'data.invalid' }),
      },
    },
    render: (_, record) => {
      console.log('record', record);

      const value = record.correct;
      return value === 0
        ? intl.formatMessage({ id: 'data.invalid' })
        : value === 1
        ? intl.formatMessage({ id: 'data.effective' })
        : '-';
    },
  };

  const columns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }), // 序号
      key: 'index',
      valueType: 'index',
      width: 60,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({ id: 'data.acquisitionTime' }), // 采集时间
      dataIndex: 'collectTime',
      key: 'collectTime',
      valueType: 'dateTimeRange',
      width: 200,
      initialValue: [dayjs().startOf('day'), dayjs()],
      render: (_, record) => {
        return <span>{record.collectTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
          };
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'data.reportingTime' }), // 上报时间
      dataIndex: 'reportTime',
      key: 'reportTime',
      hideInSearch: true,
      width: 200,
      render: (_, record) => {
        return <span>{record.reportTime}</span>;
      },
    },
    correctColumn,
    {
      title: intl.formatMessage({ id: 'data.batteryBoxName' }), // 电池箱名称
      dataIndex: 'batteryBoxName',
      key: 'batteryBoxName',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.batteryStackName' }), // 电池堆名称
      dataIndex: 'batteryStackName',
      key: 'batteryStackName',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.power' }), // 功率(kW)
      dataIndex: 'power',
      key: 'power',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.voltage' }), // 电压(V)
      dataIndex: 'voltage',
      key: 'voltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.current' }), // 电流(A)
      dataIndex: 'current',
      key: 'current',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.soc' }), // SOC(%)
      dataIndex: 'soc',
      key: 'soc',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.dischargeableCapacity' }), // 可放电量(kWh)
      dataIndex: 'dischargeCapacity',
      key: 'dischargeCapacity',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.chargeableCapacity' }), // 可充电量(kWh)
      dataIndex: 'chargeCapacity',
      key: 'chargeCapacity',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalCharge' }), // 累计充电量(kWh)
      dataIndex: 'totalCharge',
      key: 'totalCharge',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalDischarge' }), // 累计放电量(kWh)
      dataIndex: 'totalDischarge',
      key: 'totalDischarge',
      hideInSearch: true,
      width: 150,
    },
  ];

  const fetchData = async (params: {
    current: number;
    pageSize: number;
    startDate: string;
    endDate: string;
  }) => {
    setLoading(true);
    const response = await historyDataControllerBmsHistoryData({
      current: params.current,
      pageSize: params.pageSize,
      startDate: params.startDate,
      endDate: params.endDate,
      deviceCode,
      deviceType,
      areaId,
      correct: params.correct,
    });

    if (response.success && response.data && response.data?.records) {
      setData(
        response.data.records.map((record, index) => ({
          pageIndex: (params.current - 1) * params.pageSize + index + 1,
          collectTime: record.collectTime,
          reportTime: record.reportTime,
          correct: record.correct,
          batteryBoxName: record.boxName,
          batteryStackName: record.bmsName,
          power: record.power,
          voltage: record.voltage,
          current: record.current,
          soc: record.soc,
          dischargeCapacity: record.leftEnergy,
          chargeCapacity: record.usedEnergy,
          totalCharge: record.inputEnergy,
          totalDischarge: record.outputEnergy,
        })),
      );
      // @ts-ignore
      setTotal(response.data.total);
    } else {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData(params);
  }, [deviceCode, deviceType, areaId, params]);

  const handleTableChange = (pagination: { current: number; pageSize: number }) => {
    setParams((prevParams) => ({
      ...prevParams,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));
  };

  const handleSearch = (values: any) => {
    const startDate = dayjs(values.startDate);
    const endDate = dayjs(values.endDate);
    if (endDate.diff(startDate, 'day') > 31) {
      message.warning(intl.formatMessage({ id: 'data.sDays' }));
      return;
    }
    setParams((prevParams) => ({
      ...prevParams,
      startDate: values.startDate,
      endDate: values.endDate,
      correct: values.correct,
    }));
  };

  const handleReset = () => {
    setParams({
      current: 1,
      pageSize: 20,
      startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
      endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
      correct: undefined,
    });
    fetchData(params);
  };

  const scroll = {
    x: 'max-content',
    y: 'calc(100vh - 300px)',
  };

  const columnToAttrMap: Record<string, string> = {
    collectTime: 'collectTime', // 采集时间
    reportTime: 'reportTime', // 上报时间
    correct: 'correct', // 数据有效性
    batteryBoxName: 'boxName', // 电池箱名称
    batteryStackName: 'bmsName', // 电池堆名称
    power: 'power', // 功率
    voltage: 'voltage', // 电压
    current: 'current', // 电流
    soc: 'soc', // SOC
    dischargeCapacity: 'leftEnergy', // 可放电量
    chargeCapacity: 'usedEnergy', // 可充电量
    totalCharge: 'inputEnergy', // 累计充电量
    totalDischarge: 'outputEnergy', // 累计放电量
  };

  const exportDataReportFun = async (params: any) => {
    const startDate = dayjs(params.startDate);
    const endDate = dayjs(params.endDate);
    if (endDate.diff(startDate, 'day') > 3) {
      message.warning(intl.formatMessage({ id: 'data.selectTimeRange' }));
      return;
    }

    const attrNames =
      selectedColumns.length > 0
        ? selectedColumns
            .filter((col) => col !== 'index' && col !== 'pageIndex')
            .map((col) => columnToAttrMap[col] || col)
        : Object.values(columnToAttrMap);

    const exportParams: API.HistoryDataQuery = {
      areaId: Number(areaId),
      deviceType,
      deviceCode,
      startDate: dayjs(params.startDate).format('YYYY-MM-DD HH:mm:ss'),
      endDate: dayjs(params.endDate).format('YYYY-MM-DD HH:mm:ss'),
      attrNames,
    };

    await downloadFetch(exportDataReport, exportParams);
  };

  return (
    <div>
      <ProTable
        headerTitle={intl.formatMessage({ id: 'data.batteryStackInformation' })}
        search={{
          labelWidth: 80,
        }}
        columns={columns}
        scroll={scroll}
        columnsState={{
          value: Object.fromEntries(
            columns
              .filter((col) => col.dataIndex)
              .map((col) => [
                col.dataIndex,
                {
                  show:
                    selectedColumns.length === 0
                      ? true
                      : selectedColumns.includes(col.dataIndex as string),
                },
              ]),
          ),
          onChange: (stateMap) => {
            const newSelectedColumns = Object.entries(stateMap)
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              .filter(([_, value]) => value.show)
              .map(([key]) => key);
            setSelectedColumns(newSelectedColumns);
          },
          persistenceKey: 'battery-stack-info-columns',
          persistenceType: 'localStorage',
        }}
        pagination={{
          current: params.current,
          pageSize: params.pageSize,
          total,
          onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
        }}
        dataSource={data}
        loading={loading}
        onSubmit={handleSearch}
        onReset={handleReset}
        toolbar={{
          className: 'historyToobalr',
          actions: [
            <>
              <HandleBtn
                key="export"
                handleType="export"
                onClick={() => exportDataReportFun(params)}
              >
                {intl.formatMessage({ id: 'statistics.common.export' })}
              </HandleBtn>
              <Link key="monitor" to={`/stationmonitor/realtime?key=${selectedKeys}`}>
                {intl.formatMessage({ id: 'data.realtimeMonitor' })}
              </Link>
            </>,
          ],
        }}
      />
    </div>
  );
};

export default BatteryStackInfo;
